package main

import (
	"fmt"
	"influxdbDemoData/influxdb"
	"influxdbDemoData/mysql"
	"influxdbDemoData/sysinit"
	"influxdbDemoData/util"
	"github.com/astaxie/beego"
	"log"
	"strconv"
	"time"
)

var influxdbConnectWifi *influxdb.Connect
var startDate string
var endDate string

func main() {
	initMqWifi()
	dates := util.ComputeTime(startDate, endDate)
	log.Printf("startDate = %v endDate=%v", startDate, endDate)
	log.Println(dates)
	for _, date := range dates {
		//date := "2018-10-25"
		log.Println(date)
		wifis, err := mysql.FindWifiByDate(date)
		if err != nil {
			panic(err)
		}
		startTime, err := time.Parse(util.LayoutDateTime, fmt.Sprintf("%v 09:00:00", date))
		if err != nil {
			panic(err)
		}
		endTime, err := time.Parse(util.LayoutDateTime, fmt.Sprintf("%v 21:00:00", date))
		if err != nil {
			panic(err)
		}
		wifisLen := len(*wifis)
		log.Println(wifisLen)
		var wifids []*influxdb.WifiDetector
		var wifids_business []*influxdb.WifiDetector
		wifidsMap := make(map[string][]*influxdb.WifiDetector)
		for _, value := range *wifis {
			wd := influxdb.WifiDetector{
				Time:            value.DateTime,
				ZoneId:          strconv.Itoa(value.ZoneId),
				Ipaddr:          value.Ipaddr,
				Macdetected:     value.MacDetected,
				Enter:           value.Enter,
				Rssi:            value.Rssi,
				Type:            value.Type,
				Macorganization: value.Macorganization,
			}
			key := fmt.Sprintf("%v_%v", wd.ZoneId, wd.Time)
			index := len(wifidsMap[key])
			wd.Index = strconv.Itoa(index)
			wifidsMap[key] = append(wifidsMap[key], &wd)
			//fmt.Printf("%+v\n", value)
			//fmt.Printf("%+v\n", wd)
			wifids = append(wifids, &wd)
			if wd.Time.After(startTime) && wd.Time.Before(endTime) {
				wifids_business = append(wifids_business, &wd)
			}
		}
		log.Println(len(wifids))
		insert := influxdbConnectWifi.InsertWifiDetector(&wifids, influxdb.Wifidetectorigdata)
		log.Printf("--------%v insert=%v %v", date, insert, insert == len(wifids))
		log.Println(len(wifids_business))
		insert_bussiness := influxdbConnectWifi.InsertWifiDetector(&wifids_business, influxdb.Wifidetectorigdata_business)
		log.Printf("--------%v insert_bussiness=%v %v", date, insert_bussiness, insert_bussiness == len(wifids_business))
		wifis = nil
		wifids = nil
		wifids_business = nil
		//fmt.Printf("%+v\n", wifis)
	}
}
func initMqWifi() {
	beego.LoadAppConfig("ini", "./app.conf")
	sysinit.InitDatabase([]string{"mysql"})
	sysinit.InitLogs()

	//创建链接Influxdb
	iaddr := beego.AppConfig.String("influxdb::addr")
	ipassword := beego.AppConfig.String("influxdb::password")
	iusername := beego.AppConfig.String("influxdb::username")
	idbname := beego.AppConfig.String("influxdb::dbname")
	itimezone := beego.AppConfig.String("influxdb::timezone")

	influxdbConnectWifi = influxdb.NewConnect(iaddr, iusername, ipassword, idbname, itimezone)

	startDate = beego.AppConfig.String("start_data")
	endDate = beego.AppConfig.String("end_data")
}
